package org.ht.demo.openapi.mqtt;

import java.math.BigInteger;
import java.text.Format;
import com.alibaba.fastjson.JSON;

import net.sf.json.JSONObject;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.ht.demo.openapi.bean.IotHaishuiele;
import org.ht.demo.openapi.bean.IotHxmonitor;
import org.ht.demo.openapi.bean.IotXdsmokeLog;

/**
 * 鸿途科技
 * @param
 */
public class MessageCallback implements MqttCallback{
	MqttServices mqttServices=new MqttServices();


	public void deliveryComplete(IMqttDeliveryToken token) {
		System.out.println("==============mqtt消息发布状态："+token.isComplete()+"==============");
	}

	public void messageArrived(String topic, MqttMessage mmessage) {
		try {
			String[] topics = obgStrToArray(topic, "/");
			if("nh".equals(topics[1])) {
				// 消息体
				BigInteger bigInteger = new BigInteger(1, mmessage.getPayload());
				System.out.println("收到消息：：：："+bigInteger.toString(16)+"");


				JSONObject datajson = JSONObject.fromObject(hexStringToString(bigInteger.toString(16)+""));
				String deviceId=datajson.getString("deviceId").toLowerCase();   //设备deviceId
				String messageType=datajson.getString("messageType");          //消息类型


				switch (messageType) {
					case "OFFLINE":  //离线

						break;
					case "REPORT_PROPERTY":  //设备实时数据

						if("dqv1".equals(topics[2])){  //用电数据
							String msgtype=datajson.getJSONObject("properties").getString("sbtype");
							if("00".equals(msgtype)){
								IotHaishuiele haishuiele=JSON.parseObject(datajson.getJSONObject("properties").toString(),  IotHaishuiele.class);
								//用电报警状态在实体类里
								System.out.println("电气设备：："+haishuiele.toString());
							}
						}

//						if("ygv1".equals(topics[2])){  //消防火灾等设备（烟感，手报，声光，门磁，水浸，煤气、天然气气体探测）
//							IotXdsmokeLog iotXdsmokeLog = JSON.parseObject(datajson.getJSONObject("properties").toString(),IotXdsmokeLog.class);
//							System.out.println("消防火灾等设备（烟感，手报，声光，门磁，水浸，煤气、天然气气体探测）"+iotXdsmokeLog.toString());
//						}
//						if("swhv3".equals(topics[2])){  //消防水设备（水位变送器，压力变送器，消火栓）
//							IotHxmonitor  hxmonitor= JSON.parseObject(datajson.getJSONObject("properties").toString(),IotHxmonitor.class);
//							System.out.println("消防水设备（水位变送器，压力变送器，消火栓）"+hxmonitor.toString());
//						}

						break;
					default:
						break;
				}

				//消防火灾等设备（烟感，手报，声光，门磁，水浸，煤气、天然气气体探测）-事件通知   （电气火灾,跟消防水设备监测报警不在这个时间里，直接实时数据里读取）
				if(datajson.containsKey("alarmId")) {
					if("bj".equals(datajson.getJSONObject("trigger0").getString("messageType"))) {
						IotXdsmokeLog iotXdsmokeLog=new IotXdsmokeLog();
						iotXdsmokeLog.setBjcode(datajson.getJSONObject("trigger0").getString("alarmcode"));
						iotXdsmokeLog.setMac(datajson.getJSONObject("trigger0").getString("mac"));

						System.out.println("：："+iotXdsmokeLog.toString());
						if("111".equals(iotXdsmokeLog.getBjcode())) {  //

						}else if("960".equals(iotXdsmokeLog.getBjcode())) {  //

						}


					}

				}

			}
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("mqtt--"+ e);
		}
	}



	public void connectionLost(Throwable cause) {
		System.out.println("mqtt服务断开连接！！！");
		for(int i = 0; i < 10000; i++) {
			System.out.println("第【" + (i + 1) + "】次尝试连接MQTT服务");
			boolean cb = mqttServices.connect(false);
			if (cb) {
				System.out.println("mqtt服务重连成功！！！");
				for (String st : MqttServices.slist) {
					MqttServices.subScription(st,1);
				}
				break;
			}
			try {
				if(i<5){
					Thread.sleep(5000);
				}else if(i>=5 && i<10){
					Thread.sleep(10000);
				}else{
					Thread.sleep(60000);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if(i==9999){
				System.out.println("mqtt服务重连失败！！！");
			}
		}
	}


	public String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	public  String[] obgStrToArray(String str, String split) {
		String[] strArray = null;
		if (isNotNull(str)) {
			strArray = str.split(split); // 拆分字符为"," ,然后把结果交给数组strArray
		}
		return strArray;
	}

	/**
	 * 16进制转换成为string类型字符串
	 *
	 * @param s
	 * @return
	 */
	public static String hexStringToString(String s) {
		if (s == null || s.equals("")) {
			return null;
		}
		s = s.replace(" ", "");
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "UTF-8");
			new String();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}

	/**
	 * 判断是否为null
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNotNull(String str) {
		return null == str ? false : true;
	}
}
